package com.fastplatform.controller;

import com.fastplatform.entity.Menu;
import org.springframework.http.ResponseEntity;
import com.fastplatform.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import com.fastplatform.dto.MenuIdRequest;

@RestController
@RequestMapping("/menu")
@CrossOrigin(origins = "*")
public class MenuController {

    @Autowired
    private MenuService menuService;

    /**
     * 获取当前用户的菜单
     */
    @GetMapping("/current")
    public ResponseEntity<List<Menu>> getCurrentUserMenus() {
        try {
            List<Menu> menus = menuService.getCurrentUserMenus();
            return ResponseEntity.ok(menus);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 获取所有菜单（用于菜单管理）
     */
    @GetMapping("/all")
    public ResponseEntity<List<Menu>> getAllMenus(
            @RequestParam(required = false) String menuName,
            @RequestParam(required = false) Integer menuType,
            @RequestParam(required = false) Integer status) {
        try {
            List<Menu> menus = menuService.getMenuList(menuName, menuType, status);
            return ResponseEntity.ok(menus);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 保存菜单
     */
    @PostMapping("/save")
    public ResponseEntity<Menu> saveMenu(@RequestBody Menu menu) {
        try {
            Menu savedMenu = menuService.saveMenu(menu);
            return ResponseEntity.ok(savedMenu);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 删除菜单
     */
    @PostMapping("/delete")
    public ResponseEntity<String> deleteMenu(@RequestBody MenuIdRequest request) {
        try {
            menuService.deleteMenu(request.getId());
            return ResponseEntity.ok("删除成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // DTO类定义
    public static class MenuIdRequest {
        private Long id;
        public Long getId() { return id; }
        public void setId(Long id) { this.id = id; }
    }

    /**
     * 根据ID获取菜单
     */
    @GetMapping("/get")
    public ResponseEntity<Menu> getMenuById(@RequestParam Long id) {
        try {
            Menu menu = menuService.getMenuById(id);
            return ResponseEntity.ok(menu);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }
}